﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using umbraco;
using umbraco.NodeFactory;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.web;
using System.Xml;

namespace ScDataTypes.DataTypes
{
    public class BaseTreeviewDropDownListControl : UpdatePanel
    {

        #region Variables

        TextBox _TextBox;
        TreeView _Nodes;
        HyperLink _Change;
        Panel _NodePanel;

        Unit _ButtonWidth = new Unit("60px");
        public const string ImagePath = @"/umbraco/images/umbraco/";

        public event SelectionChangedDelegate SelectionChanged;
        public delegate void SelectionChangedDelegate(object sender, EventArgs e);

        #endregion

        #region Init and Constructor

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            this.EnsureChildControls();

            string strJavascript =
                @"<script type=""text/javascript"">
                  function toggleBox(id) {
                    var toggleBox = jQuery(id);
                    if (toggleBox)
                        if (toggleBox.is("":visible"")) toggleBox.hide(); else toggleBox.show();
                  }
                  </script>";

            this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "toggleBox", strJavascript);
        }

        #endregion

        #region Functions

        /// <summary>
        /// Convert object to int
        /// </summary>
        /// <param name="Value">Value to convert</param>
        /// <returns>Int representation of value</returns>
        public int ToInt(object Value)
        {
            try
            {
                if (!(Value is DBNull || Value == null))
                {
                    // Try and convert
                    int intValue;
                    if (int.TryParse(Value.ToString(), out intValue) == true)
                    {
                        return intValue;
                    }
                }
            }
            catch
            {
                // Error Handler
            }

            return 0;
        }

        /// <summary>
        /// Convert object to string
        /// </summary>
        /// <param name="Value">Value to convert</param>
        /// <returns>String representation of value</returns>
        public string ToStr(object Value)
        {
            try
            {
                if (!(Value is DBNull || Value == null))
                {
                    return Convert.ToString(Value);
                }
            }
            catch
            {
                // Error Handler
            }

            return string.Empty;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Base TreeView
        /// </summary>
        protected TreeView TreeView
        {
            get { return this._Nodes; }
        }

        /// <summary>
        /// Base Textbox
        /// </summary>
        protected TextBox TextBox
        {
            get { return this._TextBox; }
        }

        /// <summary>
        /// Selected Id
        /// </summary>
        protected string Selected
        {
            get { return this.ToStr(this.ViewState["Selected"]); }
            set { this.ViewState["Selected"] = value; }
        }

        #endregion

        #region Child Controls

        /// <summary>
        /// Create all child controls
        /// </summary>
        protected override void CreateChildControls()
        {
            // Add control to self
            Control ctlContainer = this.CreateTableControls();

            // Event Handlers
            this._Nodes.SelectedNodeChanged += new EventHandler(_Nodes_SelectedNodeChanged);
            this._Nodes.TreeNodePopulate += new TreeNodeEventHandler(_Nodes_TreeNodePopulate);

            this.ContentTemplateContainer.Controls.Add(ctlContainer);

            if (!this.Page.IsPostBack)
            {
                TreeNode objRemove = new TreeNode();
                objRemove.Text = "Remove selected";
                objRemove.Value = "0";
                objRemove.ImageUrl = ImagePath + "cancel.png";
                this._Nodes.Nodes.Add(objRemove);
            }

            // Events
            this.ChildControlsCreated();
        }

        /// <summary>
        /// Creates all controls and UI
        /// </summary>
        /// <returns>Table containing all controls</returns>
        Control CreateTableControls()
        {
            Panel pnlContainer = new Panel();
            pnlContainer.Style.Add("position", "relative");

            // Button
            this._Change = new HyperLink();
            this._Change.Text = "Change";
            
            // Create controls
            this._Nodes = new TreeView();
            this._Nodes.Width = new Unit("280px");
            this._Nodes.Height = new Unit("150px");
            this._Nodes.ShowExpandCollapse = true;
            this._Nodes.EnableClientScript = true;
            this._Nodes.ExpandDepth = 1;

            // Textbox
            this._TextBox = new TextBox();
            this._TextBox.Width = new Unit("296px");
            this._TextBox.ReadOnly = true;

            // Crete table setup
            Table tblEditor = new Table();
            TableRow rowEditor = new TableRow();
            TableCell celNodes = new TableCell();
            TableCell celOptions = new TableCell();

            this._NodePanel = new Panel();
            this._NodePanel.ID = Guid.NewGuid().ToString();
            this._NodePanel.Style.Add("position", "absolute");
            this._NodePanel.Style.Add("top", new Unit("20px").ToString());
            this._NodePanel.Style.Add("border", "1px solid #999");
            this._NodePanel.Style.Add("width", new Unit("300px").ToString());
            this._NodePanel.Style.Add("height", new Unit("150px").ToString());
            this._NodePanel.Style.Add("overflow", "auto");
            this._NodePanel.Style.Add("background-color", "white");
            this._NodePanel.Style.Add("z-index", "1000");

            celOptions.Width = new Unit("75px");
            celOptions.Style.Add("text-align", "center");

            tblEditor.CellPadding = 0;
            tblEditor.CellSpacing = 0;

            this._NodePanel.Controls.Add(this._Nodes);
            celNodes.Controls.Add(this._TextBox);
            celOptions.Controls.Add(this._Change);

            rowEditor.Cells.Add(celNodes);
            rowEditor.Cells.Add(celOptions);
            tblEditor.Rows.Add(rowEditor);

            pnlContainer.Controls.Add(tblEditor);
            pnlContainer.Controls.Add(this._NodePanel);

            return pnlContainer;
        }

        /// <summary>
        /// Child controls created override
        /// </summary>
        protected virtual new void ChildControlsCreated()
        {
        }

        #endregion

        #region Render

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            this._Change.NavigateUrl = "javascript: toggleBox('#" + this._NodePanel.ClientID + "');"; //.toggle();
            this._NodePanel.Style.Add("display", "none");
        }

        #endregion

        #region Postbacks

        void _Nodes_TreeNodePopulate(object sender, TreeNodeEventArgs e)
        {
            this.PopulateTreeView(e);
        }

        void _Nodes_SelectedNodeChanged(object sender, EventArgs e)
        {
            if (this.SelectionChanged != null) this.SelectionChanged(this, new EventArgs());
        }

        #endregion

        #region Treeview Details

        protected virtual void PopulateTreeView(TreeNodeEventArgs e)
        {
        }

        #endregion

    }
}
